using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace LS
{
    public class UnityProfabsReference : MonoBehaviour
    {

        public static UnityProfabsReference Instance
        {
            get; private set;
        }

        [SerializeField]
        private List<ReferenceItem> m_References = new List<ReferenceItem>();
        private Dictionary<string, ReferenceItem> m_ReferenceKeyMap = new Dictionary<string, ReferenceItem>();

        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
                for (int i = 0; i < m_References.Count; i++)
                {
                    m_ReferenceKeyMap.Add(m_References[i].Key, m_References[i]);
                }
            }
            else
            {
                DestroyImmediate(gameObject);
                return;
            }
        }

        public GameObject GetPrefab(string key)
        {
            if (m_ReferenceKeyMap.TryGetValue(key,out var reference))
            {
                return reference.Prefab;
            }
            return null;
        }

        public bool TryGetPrefab(string key,out GameObject prefab)
        {
            prefab = null;
            bool hasValue = m_ReferenceKeyMap.TryGetValue(key, out var reference);
            if (hasValue)
            {
                prefab = reference.Prefab;
            }
            return hasValue;
        }

        [System.Serializable]
        public class ReferenceItem
        {
            public string Key;
            public GameObject Prefab;
        }
    }
}
